package com.zaker.touchtv.modules.login;


import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.zaker.touchtv.utils.Constants;

public class LoginWebViewClient extends WebViewClient {

  public final static String LOGIN_COMMAND_FLAG = "_zkcmd";

  public final static String LOGIN_COMMAND_CLOSE = "close";

  public final static String LOGIN_USER_ID_FLAG = "_userId";

  public final static String LOGIN_TOKEN_FLAG = "token";

  public final static String LOGIN_USER_NAME_FLAG = "userName";

  private OnLoginListener mLoginListener;

  @SuppressWarnings("deprecation")
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {

    super.shouldOverrideUrlLoading(view, url);

    if (isCommandOverrideUrl(url)) {
      return true;
    }
    return false;
  }



  private boolean isCommandOverrideUrl(String url) {

    if (TextUtils.isEmpty(url)) {
      return false;
    }

    int separationIndex = url.indexOf("?&");
    if (separationIndex == -1) {
      return false;
    }

    separationIndex = url.substring(separationIndex).indexOf(LOGIN_COMMAND_FLAG);
    if (separationIndex == -1) {
      return false;
    }

    final String[] allParamPairs = url.substring(separationIndex).split("&");
    ArrayMap<String, String> keyValueMap = new ArrayMap<>(4);
    for (String paramPairs : allParamPairs) {
      final String[] keyValuePair = paramPairs.split("=");
      if (keyValuePair.length == 2) {
        keyValueMap.put(keyValuePair[0], keyValuePair[1]);
      }
    }

    Log.i(Constants.LOG_TAG, "keyValueMap: " + keyValueMap.toString());

    final String commandFlag = keyValueMap.get(LOGIN_COMMAND_FLAG);
    if (mLoginListener != null
        && TextUtils.equals(commandFlag, LOGIN_COMMAND_CLOSE)) {
      final String uid = keyValueMap.get(LOGIN_USER_ID_FLAG);
      final String userName = keyValueMap.get(LOGIN_USER_NAME_FLAG);
      mLoginListener.onFinishLoginEvent(uid, userName);
      return true;
    }

    return false;
  }

  public void setLoginListener(OnLoginListener loginListener) {
    this.mLoginListener = loginListener;
  }

  public interface OnLoginListener {
    void onFinishLoginEvent(String uid, String userName);
  }
}
